<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!-- <el-form-item label="盘点单唯一标识符" prop="id">
        <el-input
          v-model="queryParams.id"
          placeholder="请输入盘点单唯一标识符"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="盘点单号" prop="inventoryCheckNumber">
        <el-input
          v-model="queryParams.inventoryCheckNumber"
          placeholder="请输入盘点单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="计划盘点数" prop="totalQuantity">
        <el-input
          v-model="queryParams.totalQuantity"
          placeholder="请输入计划盘点数"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="已盘点数" prop="checkedQuantity">
        <el-input
          v-model="queryParams.checkedQuantity"
          placeholder="请输入已盘点数"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="未盘点数量" prop="uncheckedQuantity">
        <el-input
          v-model="queryParams.uncheckedQuantity"
          placeholder="请输入未盘点数量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:check:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:check:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:check:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:check:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="checkList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="盘点单唯一标识符" align="center" prop="id" /> -->
      <el-table-column label="盘点单号" align="center" prop="inventoryCheckNumber" />
      <el-table-column label="计划盘点数" align="center" prop="totalQuantity" />
      <el-table-column label="已盘点数" align="center" prop="checkedQuantity" />
      <el-table-column label="未盘点数" align="center" prop="uncheckedQuantity" />
			<el-table-column label="单据状态" align="center" prop="State">
				<template slot-scope="scope">
					<span v-if="scope.row.State=='盘点中'" style="color: orange;">盘点中</span>
					<span v-if="scope.row.State=='盘点完成'" style="color: green;">盘点完成</span>
				</template>
			</el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:check:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:check:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用于存储盘点单信息的对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="盘点单号" prop="inventoryCheckNumber">
          <el-input v-model="form.inventoryCheckNumber" placeholder="请输入盘点单号" disabled/>
        </el-form-item>
        <el-form-item label="计划盘点数" prop="totalQuantity" >
          <el-input v-model="form.totalQuantity" placeholder="请输入计划盘点数" disabled/>
        </el-form-item>
        <el-form-item label="已盘点数" prop="checkedQuantity">
          <el-input v-model="form.checkedQuantity" placeholder="请输入已盘点数" disabled/>
        </el-form-item>
        <el-form-item label="未盘点数" prop="uncheckedQuantity">
          <el-input v-model="form.uncheckedQuantity" placeholder="请输入未盘点数" disabled/>
        </el-form-item>
       <!-- <el-form-item label="删除标志" prop="delFlag">
          <el-input v-model="form.delFlag" placeholder="请输入删除标志" />
        </el-form-item> -->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
	  <!--明细表-->
	  <div>
	  	<label>明细</label>
	  </div>
	  <div style="width: 100%; padding: 5px">
	  	<el-button @click="AddMingXi" type="primary" size="mini" icon="el-icon-plus" v-if="IsUpdate">新增</el-button>
	  </div>
	  <el-table border :data="InfoList" style="width: 100%" height="400">
	  	<!-- <el-table-column prop="id" label="序号" width="50" type="index" align="center" :index="index=>index+1" /> -->
	  	<el-table-column label="图片" align="center" prop="image" >
	  		<el-image slot-scope="scope" :src="ApiUrl+scope.row.image"></el-image>
	  	</el-table-column>
	  	<el-table-column prop="rfidNumber" label="rfid编码" align="center" >
	  		<template v-slot="scope">
	  			<span>{{ scope.row.rfidNumber }}</span>
	  		</template>
	  	</el-table-column>
	  	<el-table-column prop="productName" label="名称" align="center" >
	  		<template v-slot="scope">
	  			<span>{{ scope.row.productName }}</span>
	  		</template>
	  	</el-table-column>
	  	<el-table-column prop="registrationNumber" label="总登记号" align="center">
	  		<template v-slot="scope">
	  			<span>{{ scope.row.registrationNumber }}</span>
	  		</template>
	  	</el-table-column>
	  	<el-table-column prop="productTypeIdName" label="分类号" align="center">
	  		<template v-slot="scope">
	  			<span>{{ scope.row.productTypeIdName }}</span>
	  		</template>
	  	</el-table-column>
	  	<el-table-column prop="categoryNumber" label="分类号详情" align="center">
	  		<template v-slot="scope">
	  			<span>{{ scope.row.categoryNumber }}</span>
	  		</template>
	  	</el-table-column>
	  	<el-table-column prop="eraName" label="年代" align="center">
	  		<template v-slot="scope">
	  			<span>{{ scope.row.eraName }}</span>
	  		</template>
	  	</el-table-column>
	  	<el-table-column prop="warehouseIdNmae" label="方位" align="center">
	  		<template v-slot="scope">
	  			<span>{{ scope.row.warehouseIdNmae }}</span>
	  		</template>
	  	</el-table-column>
	  	<el-table-column prop="orientation" label="方位详情" align="center">
	  		<template v-slot="scope">
	  			<span>{{ scope.row.orientation }}</span>
	  		</template>
	  	</el-table-column>
	  	<el-table-column prop="quantity" label="数量" align="center">
	  		<template v-slot="scope">
	  			<span>{{ scope.row.quantity }}</span>
	  		</template>
	  	</el-table-column>
	  	<el-table-column prop="completenessName" label="完残程度" align="center">
	  		<template v-slot="scope">
	  			<span>{{ scope.row.completenessName }}</span>
	  		</template>
	  	</el-table-column>
	  	
	  	<el-table-column prop="collectionLevelName" label="藏品级别" align="center">
	  		<template v-slot="scope">
	  			<span>{{ scope.row.collectionLevelName }}</span>
	  		</template>
	  	</el-table-column>
	  	<el-table-column prop="material" label="质地" align="center">
	  		<template v-slot="scope">
	  			<span>{{ scope.row.material }}</span>
	  		</template>
	  	</el-table-column>
	  	<el-table-column prop="createByName" label="登录人" align="center">
	  		<template v-slot="scope">
	  			<span>{{ scope.row.createByName }}</span>
	  		</template>
	  	</el-table-column>
	  	
	  	<el-table-column label="藏品状态" align="center" prop="productStatus" >
	  		<template slot-scope="scope">
	  			<span style="color: #ff0000;" v-if="scope.row.productStatus=='未入库'">未入库</span>
	  			<span style="color: green;" v-if="scope.row.productStatus=='在库'">在库</span>
	  			<span style="color: orange;" v-if="scope.row.productStatus=='已出库'">已出库</span>
	  			<span style="color: red;" v-if="scope.row.productStatus=='非法领用'">非法领用</span>
	  		</template>
	  	</el-table-column>
	  	
	  	<el-table-column label="发卡状态" align="center" prop="fkStatus" >
	  		<template slot-scope="scope">
	  			<span style="color: #ff0000;" v-if="scope.row.fkStatus=='未发卡'">未发卡</span>
	  			<span style="color: green;" v-if="scope.row.fkStatus=='已发卡'">已发卡</span>
	  		</template>
	  	</el-table-column>
		<el-table-column label="盘点状态" align="center" prop="inventoryStatus" >
			<template slot-scope="scope">
				<span style="color: #ff0000;" v-if="scope.row.inventoryStatus=='未盘点'">未盘点</span>
				<span style="color: green;" v-if="scope.row.inventoryStatus=='已盘点'">已盘点</span>
			</template>
		</el-table-column>
	  	<el-table-column label="操作" width="50" align="center" v-if="IsUpdate" >
	  		<template v-slot="scope">
	  			<div style="display: flex;">
	  				<el-button size="small" icon="Delete" type="text"
	  					@click="delVersion(scope.row,scope.$index)">删除
	  				</el-button>
	  			</div>
	  		</template>
	  	</el-table-column>
	  </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
	<!--  明细新增弹窗-->
	<el-dialog title="新增明细" :visible.sync="openMingXi" width="80%" append-to-body :close-on-click-modal="false">
		<el-form :model="queryParamsMingXi" ref="queryFormMingXi" size="small" :inline="true" v-show="showSearch"
			label-width="68px">
			<!-- <el-form-item label="资产类别" prop="productTypeId">
				<el-select v-model="queryParamsMingXi.productTypeId" placeholder="请选择资产类别">
					<el-option v-for="item in productTypeList" :key="item.id" :label="item.productTypeName"
						:value="item.id">
					</el-option>
				</el-select>
			</el-form-item> -->
			<el-form-item label="仓库" prop="warehouseId">
				<el-select v-model="queryParamsMingXi.warehouseId" placeholder="请选择仓库">
					<el-option v-for="item in warehouseList" :key="item.id" :label="item.warehouseName"
						:value="item.id">
					</el-option>
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQueryMingXi">搜索
				</el-button>
				<el-button icon="el-icon-refresh" size="mini" @click="resetQueryMingXi">重置</el-button>
			</el-form-item>
		</el-form>
		<el-table v-loading="loading" :data="warehousingDetail" @selection-change="handleSelectionChangeMingXi"
			height="600" :row-key="binrowkey">
			<el-table-column type="selection" width="55" align="center" :reserve-selection="true"/>
			<el-table-column label="图片" align="center" prop="image">
				<el-image slot-scope="scope" :src="ApiUrl+scope.row.image"></el-image>
			</el-table-column>
			<el-table-column label="名称" align="center" prop="productName" />
			<el-table-column label="总登记号" align="center" prop="registrationNumber" />
			<el-table-column label="rfid编号" align="center" prop="rfidNumber" />
			<el-table-column label="分类号" align="center" prop="productTypeIdName" />
			<el-table-column label="分类号详情" align="center" prop="categoryNumber" />
			<el-table-column label="年代" align="center" prop="eraName" />
			<el-table-column label="方位" align="center" prop="warehouseIdNmae" />
			<el-table-column label="方位详情" align="center" prop="orientation" />
			<el-table-column label="数量" align="center" prop="quantity" />
			<el-table-column label="完残程度" align="center" prop="completenessName" />
			<el-table-column label="藏品级别" align="center" prop="collectionLevelName" />
			<el-table-column label="审核人" align="center" prop="approverName" />
			<el-table-column label="质地" align="center" prop="material" />
			<el-table-column label="登录人" align="center" prop="createByName" />
			<el-table-column label="藏品状态" align="center" prop="productStatus" >
				<template slot-scope="scope">
					<span style="color: #ff0000;" v-if="scope.row.productStatus=='未入库'">未入库</span>
					<span style="color: green;" v-if="scope.row.productStatus=='在库'">在库</span>
					<span style="color: orange;" v-if="scope.row.productStatus=='已出库'">已出库</span>
					<span style="color: #ff0000;" v-if="scope.row.productStatus=='非法出库'">非法出库</span>
				</template>
			</el-table-column>
			<el-table-column label="发卡状态" align="center" prop="fkStatus"  >
				<template slot-scope="scope">
					<span style="color: #ff0000;" v-if="scope.row.fkStatus=='未发卡'">未发卡</span>
					<span style="color: green;" v-if="scope.row.fkStatus=='已发卡'">已发卡</span>
				</template>
			</el-table-column>
		</el-table>
		<pagination v-show="totalMingXi>0" :total="totalMingXi" :page.sync="queryParamsMingXi.pageNum"
			:limit.sync="queryParamsMingXi.pageSize" @pagination="SelectMingXi" />
		<div slot="footer" class="dialog-footer">
			<el-button type="primary" @click="submitFormMingXi">确 定</el-button>
			<el-button @click="cancelMingXi">取 消</el-button>
		</div>
	</el-dialog>
  </div>
</template>

<script>
import { listCheck, getCheck, delCheck, addCheck, updateCheck,listPD,listWarehouse,listType } from "@/api/system/check";

export default {
  name: "Check",
  data() {
    return {
		// Api
		ApiUrl: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用于存储盘点单信息的表格数据
      checkList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        id: null,
        inventoryCheckNumber: null,
        totalQuantity: null,
        checkedQuantity: null,
        uncheckedQuantity: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
	  // 入库明细数组
	  InfoList:[],
	  // 明细查询参数
	  queryParamsMingXi: {
	  	pageNum: 1,
	  	pageSize: 10,
		productTypeId:null,
		warehouseId:null
	  },
	  warehousingDetail: [],
	  totalMingXi:0,
	  //选中的明细数据
	  SelectInfoList: [],
	  openMingXi:false,
	  IsUpdate:false,
		warehouseList:[],
		productTypeList:[]
    };
  },
  created() {
    this.getList();
	// 获取仓库列表
	this.listWarehouse();
	// 获取类别列表
	this.GetproductTypeList();
  },
  methods: {
	  // 获取仓库列表
	  listWarehouse() {
	  	listWarehouse().then(response => {
	  		console.log("仓库列表", response)
	  		this.warehouseList = response.rows;
	  	});
	  },
	  // 获取类别
	  GetproductTypeList(){
	  	listType().then(response => {
	  		console.log("类别列表", response)
	  		this.productTypeList = response.rows;
	  	});
	  },
	  
	  
	  // 点击新增明细事件
	  AddMingXi() {
	  	this.openMingXi = true;
	  	this.SelectMingXi();
	  },
	  /** 查询库存列表信息*/
	  SelectMingXi() {
	  	console.log("99999999999")
	  	listPD(this.queryParamsMingXi).then(response => {
	  		console.log(response);
	  		this.warehousingDetail = response.rows;
	  		this.totalMingXi = response.total;
	  	});
	  },
    /** 查询用于存储盘点单信息的列表 */
    getList() {
      this.loading = true;
      listCheck(this.queryParams).then(response => {
        this.checkList = response.rows;
		console.log(response)
				this.checkList.forEach(function(res) {
					res.uncheckedQuantity=res.totalQuantity-res.checkedQuantity
					if (res.uncheckedQuantity > 0) {
						// 入库中
						res['State'] = '盘点中';
					}
					if (res.uncheckedQuantity == 0) {
						// 入库完成
						res['State'] = '盘点完成';
					}
				})
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        inventoryCheckNumber: null,
        totalQuantity: null,
        checkedQuantity: null,
        uncheckedQuantity: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
	// 搜索明细
	handleQueryMingXi() {
		this.queryParamsMingXi.pageNum = 1;
		this.SelectMingXi();
	},
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
	//重置明细搜索
	resetQueryMingXi() {
		this.resetForm("queryFormMingXi");
		this.handleQueryMingXi();
	},
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "创建盘点单";
	  this.InfoList = [];
	  // 生成入库单单号
	  this.form.inventoryCheckNumber = this.orderCode();
	  this.IsUpdate = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCheck(id).then(response => {
        this.form = response.data;
		console.log("盘点明细",response)
		this.InfoList = response.data.infoListS
        this.open = true;
        this.title = "查看盘点单";
      });
    },
    /** 提交按钮 */
    submitForm() {
		if (this.InfoList.length <= 0) {
			this.$message({
				showClose: true,
				message: '请添加需要盘点的明细',
				type: 'warning'
			});
			return;
		}
		
		this.$confirm('请仔细复核盘点信息，创建后将无法进行修改，确认创建此盘点单？', '提示', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning'
		}).then(() => {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCheck(this.form,this.InfoList).then(response => {
              this.$modal.msgSuccess("修改成功");
			  this.InfoList = [];
              this.open = false;
              this.getList();
            });
          } else {
            addCheck(this.form,this.InfoList).then(response => {
              this.$modal.msgSuccess("新增成功");
			  this.InfoList = [];
              this.open = false;
              this.getList();
            });
          }
        }
      });
	   });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除盘点单的编号为"' + ids + '"的数据项？').then(function() {
        return delCheck(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/check/export', {
        ...this.queryParams
      }, `check_${new Date().getTime()}.xlsx`)
    },
	//多选框选中明细数据
	handleSelectionChangeMingXi(selection) {
		console.log("选中的明细数据", selection)
		this.SelectInfoList = selection;
	},
	//确认明细数据
	submitFormMingXi() {
		this.InfoList = this.InfoList.concat(this.SelectInfoList);
		this.InfoList = this.unique(this.InfoList, 'rfidNumber');
		this.openMingXi = false;
		this.form.totalQuantity = this.InfoList.length
	},
	//明细取消按钮
	cancelMingXi() {
		this.openMingXi = false;
	},
	// 对象数组去重
	unique(arr, prop) {
		let obj = {};
		return arr.reduce(function(preValue, item) {
			obj[item[prop]] ? '' : obj[item[prop]] = true && preValue.push(item);
			return preValue
		}, [])
	
	},
	//删除明细数据
	delVersion(data, index) {
		console.log("删除的数据", data);
		console.log("删除的索引值", index)
		this.$confirm('是否删除此明细', '提示', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning'
		}).then(() => {
			this.InfoList.splice(index, 1);
			this.$message({
				type: 'success',
				message: '删除成功!'
			});
			this.form.totalQuantity = this.InfoList.length
		});
	
	},
	/**
	 * #JS生成订单号的函数
	 * @param 
	 * @return string 生成的订单号
	 */
	orderCode(){
	   const now = new Date();
	       let month = now.getMonth() + 1;
	       let day = now.getDate();
	       let hour = now.getHours();
	       let minutes = now.getMinutes();
	       let seconds = now.getSeconds();
	       // month = setTimeDateFmt(month);
	       // day = setTimeDateFmt(day);
	       // hour = setTimeDateFmt(hour);
	       // minutes = setTimeDateFmt(minutes);
	       // seconds = setTimeDateFmt(seconds);
	       let orderCode = now.getFullYear().toString() + month.toString() + day + hour + minutes + seconds ;
	       return orderCode;
	},
	binrowkey(row){
		return row.id;
	},
  }
};
</script>
